<?php
/**
 *
 * Orm.php
 * User: kalvin
 * Date: 2018/2/1
 * Time: 下午3:02
 */

namespace Core;


/**
 * Class Orm
 * @package Core
 * ORM 父类方法
 */
class Orm
{
    private $className;
    private $server;
    private $type;
    private $username;
    private $password;
    private $port;
    private $dbname;
    private $charset;
    private $_pdo;
    private $where=' 1 ';
    private $limit='';
    public function __construct()
    {

        $holeClassName=get_called_class(); //App\Entity\Users
        $arr=explode('\\',$holeClassName);
        $this->className=strtolower($arr[count($arr)-1]);
        //根据配置文件项连接数据库
        $this->server=$GLOBALS['conf']['mysql']['server'];
        $this->type=$GLOBALS['conf']['mysql']['type'];
        $this->username=$GLOBALS['conf']['mysql']['username'];
        $this->password=$GLOBALS['conf']['mysql']['password'];
        $this->port=$GLOBALS['conf']['mysql']['port'];
        $this->dbname=$GLOBALS['conf']['mysql']['dbname'];
        $this->charset=$GLOBALS['conf']['mysql']['charset'];
        $this->connect();
    }
    public function connect(){
        $dsn="$this->type:host=$this->server;dbname=$this->dbname;port=$this->port;charset=$this->charset";
        $this->_pdo=new \PDO($dsn,$this->username,$this->password);
        $this->_pdo->setAttribute(\PDO::ATTR_ERRMODE, \PDO::ERRMODE_EXCEPTION);
    }

    public function select()
    {
        $sql='select * from '.$this->className;
        $res=$this->query($sql);
        return $res->fetchAll(\PDO::FETCH_ASSOC);
    }

    public function query($sql)
    {
        try{
            $resObj=$this->_pdo->query($sql);
        }catch (\PDOException $e){
           $resObj=$this->errors($e,$sql);
        }
        return $resObj;
    }

    public function errors($e,$sql)
    {
        echo '错误信息为：'.$e->getMessage().'<br/>';
//        echo '错误代码为：'.$e->errorCode() ().'<br/>';
        echo '错误语句为：'.$sql.'<br/>';
        return false;
    }

    /**
     * @return mixed
     * 连贯操作的 get方法
     */
    public function get()
    {
        $sql='select * from '.$this->className.' where';
        $sql.=$this->where;
        $res=$this->query($sql);
        return $res->fetchAll(\PDO::FETCH_ASSOC);
    }

    /**
     * @param $field 字段名
     * @param $operator 符号，> < = >= eq等等。。
     * @param $condition 数值或字符串
     * 用户连贯操作的where方法
     */
    public function where($field,$operator,$condition)
    {
        //如果strlen==3 就是说 之前无where 条件不然就直接
        if (strlen($this->where)==3){
            $this->where=' '.$field.' '.$operator.' '.$condition.' ';
            return $this;
        }
        $this->where.=' and '.$field.' '.$operator.' '.$condition.' ';
        return $this;
    }
}